<script lang="ts" setup>
  import { onMounted, ref, watch } from 'vue';
  import { useSalesStore, useSystemStore } from '@/store';

  const props = defineProps<{ defaultAccount?: boolean }>();

  const list = ref<any>([]);
  const salesStore = useSalesStore();
  const systemStore = useSystemStore();
  const searchForm = ref<any>({});
  const emit = defineEmits(['select']);
  const visible = defineModel<boolean>('visible');
  const model = defineModel();
  const label = ref('');

  async function fetchList() {
    if (list.value.length > 0) {
      return;
    }
    list.value = await salesStore.getSales(searchForm.value);
  }

  watch(
    () => model.value,
    async (val) => {
      await fetchList();
      if (val) {
        label.value = list.value.find((item: any) => item.id === Number(val))?.realName;
      } else {
        label.value = '';
      }
    },
    { immediate: true }
  );

  onMounted(async () => {
    await fetchList();
    if (props.defaultAccount) {
      const defaultSalesmanId = systemStore.getValue('System', 'DefaultSalesman');
      if (defaultSalesmanId) {
        label.value = list.value.find((item: any) => item.id === Number(defaultSalesmanId))?.realName;
      }
    }
  });

  function handleSelect(record: any) {
    visible.value = false;
    model.value = record.id;
    label.value = record.realName;
  }
</script>

<template>
  <div class="sales-picker">
    <a-space fill>
      <a-input placeholder="请选择销售人员" v-model="label" />
      <a-button type="primary" @click="visible = true">选择</a-button>
    </a-space>
    <a-modal :visible="visible" title="选择销售员" @cancel="visible = false" :footer="false">
      <a-table :data="list">
        <template #columns>
          <a-table-column title="编号" :width="80" data-index="id"></a-table-column>
          <a-table-column title="销售人员" data-index="realName"></a-table-column>
          <a-table-column title="操作" :width="120">
            <template #cell="{ record }">
              <a-space>
                <a-button type="primary" @click="handleSelect(record)" size="small">选择</a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
  .sales-picker {
    width: 100%;

    ::v-deep(.arco-space-item:first-child) {
      flex: 1;
    }
  }
</style>
